/** @format */

import React, { useEffect, useState } from "react";
import request from "../../api/request";
import { message, Table, Input, Button, Modal, Form } from "antd";
import html2pdf from "html2pdf.js";
import TableFilter from "../../components/SearchInput";
import { Link } from "react-router-dom";

/**
 * 模块化的作用
 * 1:方便多人协作开发，避免变量污染的问题
 * 2:方便后续代码修改，增加功能等;
 * 模块化的发展历程
 * 1:一开始使用闭包+自执行函数来进行划分空间，让某一块js保持独立私密性的--所谓的模块化
 * 2:有大佬制定了一个模块化的规范，commenjs规范,  规定了导入导出的方式
 *  导出:module.exports = {}
 *  导入:require();------主要是用于node.js里面;
 * 3:又有一些大佬，制定了amd规范,  规定了导入导出的方式
 *  导出:define([],function(){})
 *  导入:require([],function(){});
 *  其中的代表作就是require.js;
 * 4:又有另外一个大佬,制定了cmd规范, 规定了导入导出的方式
 *  导出:define([],function(){});
 *  导入:require([],function(){});
 *  其中的代表作就是sea.js;
 * 5:官方出手了,  制定了es6的模块化规范,  规定了导入导出的方式
 *  导出:export {}
 *  导入:import {} from "";
 */
// const ExportJsonExcel = require("js-export-excel");
import ExportJsonExcel from "js-export-excel";
const { confirm } = Modal;
const Dashboard = () => {
  const [articleList, setArticleList] = useState([]);
  //因为这个接口的容错原因，在设置keyword和tag初始值的时候，设置为null
  //usestate定义初始值的时候，如果想要给初始值一个类型的话，需要在<>中指定类型
  // const [keyword, setKeyword] = useState<any>(null);
  // const [tag, setTag] = useState<any>(null);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [bb] = Form.useForm();
  const [id, setId] = useState<any>(null);
  //定义一个状态来表示当前是点击的新增还是编辑
  const [uiadd, setUiadd] = useState("");
   const [msgApi, msgHolder] = message.useMessage();
  /**
   * 设置编辑时候的回显的状态--受控组件的形式
   */
  // let [title,setTitle] = useState<any>(null);
  // let [content,setContent] = useState<any>(null);
  // let [tagInput,setTagInput] = useState<any>(null);
  //先获取一下列表数据;
  const getArticleList = async (
    pageNum = 1,
    pageSize = 10,
    keyword: any = null,
    tag: any = null,
    createTime: any = ""
  ) => {
    const res = await request.get("/article/list", {
      params: {
        page: pageNum,
        pageSize,
        keyword,
        tag,
      },
    });
    console.log(res);
    setArticleList(res.data.rows);
    setTotal(res.data.count);
  };
  useEffect(() => {
    getArticleList();
  }, []);
  const del = (rows: any) => {
    console.log(rows);
    //点击删除按钮，出现气泡框，点击确定进行删除
    confirm({
      title: "确认删除吗?",
      okText: "确认",
      okType: "danger",
      onOk: async () => {
        //从articlelist数据里面找到这一项给删除掉;
        const newList = articleList.filter((item: any) => item.id !== rows.id);
        setArticleList(newList);
      },
      onCancel: () => {
        console.log("Cancel");
      },
    });
  };

  //编辑
  const editfn = (rows: any) => {
    console.log(rows);
    //设置编辑时候的回显的状态--受控组件的形式
    // setTitle(rows.title);
    // setContent(rows.content);
    // setTagInput(rows.tag);
    setUiadd("edit");
    setId(rows.id);
    bb.setFieldsValue({
      title: rows.title,
      content: rows.content,
    });
    setIsModalOpen(true);
  };

  const handleOk = async (e) => {
    setIsModalOpen(false);
    await bb.validateFields();
    const values = await bb.getFieldsValue();
    //   console.log(values);
    //  console.log(e)
    //区分当前弹框是新增还是编辑;

    if (uiadd === "add") {
      //新增
      const res = await request.post("article", {
        title: values.title,
        content: values.content,
        tagList: ["HTTP"],
        categoryList: ["HTTP"],
        authorId: 47529555,
      });
      msgApi.success("新增成功");
    } else {
      const res = await request.put(`article/${id}`, {
        title: values.title,
        content: values.content,
        tagList: ["HTTP"],
        categoryList: ["HTTP"],
      });
      msgApi.success("编辑成功");
    }

    getArticleList();
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const columns = [
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
    },
    {
      title: "文章标题",
      // dataIndex: "title",
      key: "title",
      render: (rows: any) => {
        return <Link to={`/home/detail/${rows.id}`}>{rows.title}</Link>;
      },
    },
    {
      title: "阅读数量",
      dataIndex: "viewCount",
      key: "id",
    },
    {
      title: "操作",
      key: "id",
      render: (rows: any) => {
        return (
          <div>
            <Button
              type="primary"
              onClick={() => {
                editfn(rows);
              }}
            >
              编辑
            </Button>
            <Button
              type="link"
              onClick={() => {
                del(rows);
              }}
            >
              删除
            </Button>
          </div>
        );
      },
    },
  ];
  const searchFn = (values: any) => {
    getArticleList(1, 10, values.keyword, values.tag, values.createTime);
  };
  const resetFn = () => {
    getArticleList();
  };
  const addFn = () => {
    setUiadd("add");
    setId(null);
    bb.setFieldsValue({
      title: "",
      content: "",
    });
    setIsModalOpen(true);
  };
  /**
   * 受控组件
   * 受控组件---表示表单控件元素的value值，受到当前组件定义的状态所控制;
   * 怎么实现受控组件
   * 1. 给表单控件元素添加value属性，值为当前组件定义的状态;
   * 2. 给表单控件元素添加onChange事件，事件处理函数中，调用当前组件定义的状态更新函数，更新状态值为事件对象的target.value属性值;
   */
  const exportExcel = () => {
    const opts = {
      fileName: "刘德华",
      datas: [
        {
          sheetData: articleList,
          sheetName: "文章列表",
          //导出的数据源当中的哪些字段
          sheetFilter: ["createdAt", "title", "viewCount"],
          sheetHeader: ["创建时间", "文章标题", "阅读数量"],
        },
      ],
    };
    var toExcel = new ExportJsonExcel(opts); //new
    toExcel.saveExcel(); //保存
  };
  const savepdf = () => {
    //1:获取需要导出的这个表格的dom节点
    var element: any = document.getElementById("tableid");
    //2:配置导出的参数
    var opt: any = {
      //margin表示导出的pdf文件的边距
      margin: 1,
      //filename表示导出的pdf文件的文件名
      filename: "lalala.pdf",
      //image表示导出的pdf文件的图片类型
      image: { type: "jpeg", quality: 0.98 },
      //表示缩放比
      html2canvas: { scale: 2 },
      //导出的pdf的格式
      jsPDF: { unit: "in", format: "a4", orientation: "portrait" },
    };
    //3:执行导出
    html2pdf().set(opt).from(element).save();
  };
  return (
    <div>
      <div className="search-container">
        <div className="search-form">
          {/* <Input
            className="search-input"
            placeholder="请输入文章标题"
            value={keyword}
            onChange={(e) => setKeyword(e.target.value)}
          />
          <Input
            className="search-input"
            placeholder="请输入标签"
            value={tag}
            onChange={(e) => setTag(e.target.value)}
          />
          <Button className="search-button" type="primary" onClick={searchFn}>
            搜索
          </Button> */}
          <TableFilter
            showKeywordFilter={false}
            showTagFilter={true}
            showCreateTimeFilter={true}
            onSearch={searchFn}
            onReset={resetFn}
          />
          <Button className="search-button" type="primary" onClick={addFn}>
            新增
          </Button>
          <Button type="primary" onClick={savepdf}>
            导入为pdf
          </Button>
          <Button type="primary" onClick={exportExcel}>
            导出为excel
          </Button>
        </div>
      </div>
      <Table
        id="tableid"
        dataSource={articleList}
        columns={columns}
        rowKey="id"
        pagination={{
          total,
          current: current,
          pageSize: pageSize,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          onChange: (page, size) => {
            console.log(page, size, "当前分页的页码");
            setCurrent(page);
            getArticleList(page, size);
          },
          onShowSizeChange: (current, size) => {
            console.log(current, size, "改变每页条数");
            setCurrent(1); // 重置到第一页
            setPageSize(size); // 更新pageSize状态
            getArticleList(1, size);
          },
        }}
      />

      <Modal
        title={uiadd === "add" ? "新增文章" : "编辑文章"}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        {/* <Input placeholder="请输入文章标题" value={title} onChange={(e)=>setTitle(e.target.value)} />
           <Input placeholder="请输入文章内容" value={content} onChange={(e)=>setContent(e.target.value)} />
           <Input placeholder="请输入标签" value={tagInput} onChange={(e)=>setTagInput(e.target.value)} /> */}
        <Form form={bb} name="basic" autoComplete="off">
          <Form.Item
            label="文章标题"
            name="title"
            rules={[{ required: true, message: "请输入文章标题" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="文章内容"
            name="content"
            rules={[{ required: true, message: "请输入文章内容" }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Dashboard;
